package servlet;


import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private static final String KAPTCHA_SESSION_KEY = "HOME_KAPTCHA_SESSION_KEY";
    private static final String KAPTCHA_SESSION_DATE = "HOME_KAPTCHA_SESSION_DATE";
    private static final Long SESSION_TIMEOUT = 60 * 1000L;
    private String inputCaptcha="inputCaptcha";
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session=req.getSession();
        String captcha = req.getParameter("inputCaptcha");  // 获取验证码
        String userName = req.getParameter("username");    // 获取用户名
        String password = req.getParameter("password");    // 获取密码
        String confirmPassword = req.getParameter("confirm-password"); // 获取确认密码
        String saveCaptcha=(String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);

        if(!password.equals(confirmPassword)){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("你输入的密码前后不一致");
        }
        if(captcha.length()==0){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("请输入您的验证码");
        }if(!captcha.equals(saveCaptcha)){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("验证码输入不正确");
        }
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        try {
            connection= DBUtil.getConnection();
            String sql="INSERT INTO user (username, password) VALUES (?, ?)";
            statement =connection.prepareStatement(sql);
            statement.setString(1,userName);
            statement.setString(2,password);
            statement.executeUpdate();
            resp.sendRedirect("login.html");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
